package com.ssi.mrms.dao.Impl;

import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import com.ssi.mrms.model.DataTableModel;

public class BaseDaoImpl<T> {
	final static String SQL = "select * from {0} {1} {2} limit {3},{4}";
	final static String SQL_COUNT = "select count(*) as total from {0} {1}";

	public DataTableModel<T> limit(final String tableName, final SQLWhere[] sqlWheres, final String[] sqlOrderBys,
			int page, int perPage, JdbcTemplate jdbcTemplate, RowMapper<T> mapper) {
		DataTableModel<T> dataTableModel = new DataTableModel<>();

		String sqlWhere = " where 1 = 1 ";
		List<Object> params = new ArrayList<>();
		if (sqlWheres != null) {
			for (SQLWhere sqlWhere2 : sqlWheres) {
				if(sqlWhere2.getValue() instanceof Date){
					sqlWhere += MessageFormat.format(" and date({0}) {1} date(?) ", sqlWhere2.getKey(), sqlWhere2.getOperation()
							.getValue());
					params.add(sqlWhere2.getValue());
				}else{
				sqlWhere += MessageFormat.format(" and {0} {1} ? ", sqlWhere2.getKey(), sqlWhere2.getOperation()
						.getValue());
				params.add(sqlWhere2.getValue());
				}
				
			}
		}
		String sqlOrderBy = sqlOrderBys == null || sqlOrderBys.length == 0 ? "" : " order by "
				+ StringUtils.join(sqlOrderBys, ",");
		String sql = MessageFormat.format(SQL, new Object[] { tableName, sqlWhere, sqlOrderBy, page, perPage });
		List<T> lists = jdbcTemplate.query(sql, params.toArray(new Object[0]), mapper);
		if (lists == null || lists.isEmpty()) {
			lists = new ArrayList<>();
		}
		String sqlCount = MessageFormat.format(SQL_COUNT, new Object[] { tableName, sqlWhere });
		Integer count = jdbcTemplate.query(sqlCount, params.toArray(new Object[0]), new ResultSetExtractor<Integer>() {
			@Override
			public Integer extractData(java.sql.ResultSet rs) throws SQLException, DataAccessException {
				if (rs.next()) {
					return rs.getInt("total");
				}
				return null;
			}
		});
		dataTableModel.setItems(lists);
		dataTableModel.setTotal(count);
		dataTableModel.setIndex(page);
		dataTableModel.setLength(perPage);
		return dataTableModel;
	}

//	public static void main(String[] args) {
//		BaseDaoImpl<AvlModel> daoImpl = new BaseDaoImpl<>();
//		daoImpl.limit("tbl_avl", new SQLWhere[0], new String[0], 0, 10, null, new AvlMapping());
//	}

}
